package com.ruiaa.meeting.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ruiaa.meeting.common.CommonResponse;
import com.ruiaa.meeting.common.Constant;
import com.ruiaa.meeting.model.Api;
import com.ruiaa.meeting.model.User;
import com.ruiaa.meeting.persistence.UserMapper;
import com.ruiaa.meeting.service.AdminService;
import com.ruiaa.meeting.service.ApiService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.StringTokenizer;

@Service("adminService")
@Slf4j
public class AdminServiceImpl implements AdminService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
   private ApiService apiService;

    @Override
    public CommonResponse<User> addUser(String username,String password){
        if(username == null || password == null){
            log.error(" at user ,parameter is null");
            return CommonResponse.createForError(" at user ,parameter is null");
        }

        User newUser = new User();
        newUser.setUsername(username);
        newUser.setPassword(password);
        newUser.setRole(Constant.Role.USER);
        newUser.setState(Constant.USER_STATE.ABLE);

        int rows = userMapper.insert(newUser);
        if(rows == 0){
            return CommonResponse.createForError("add failed");
        }
        List<Api> relationalApis = apiService.getRelationalApis(9);
        return CommonResponse.createForSuccessIncludeApis(newUser, relationalApis);

    }

    @Override
    public CommonResponse<Object> deleteUser(String username) {
       if(username == null){
           log.error("at deleteUser, username is null");
           return CommonResponse.createForError("delete failed,username is null");
       }
       User user = userMapper.selectById(username);
       if(user.getRole().equals(Constant.Role.USER)){
           int rows = userMapper.deleteById(username);
           if(rows == 0){
               return CommonResponse.createForError("add failed");
           }
           return CommonResponse.createForSuccess("delete safe");
       }
       else return CommonResponse.createForError("admin can just delete user");

    }

    @Override
    public CommonResponse<Object> updateUser(User user) {
       if(user == null){
           log.error("at updateUser, user object is null");
           return CommonResponse.createForError("update user failed");
       }
       if(Objects.equals(user.getRole(), Constant.Role.USER)){

           UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
           updateWrapper.eq("username",user.getUsername());
           //在这里是不允许修改用户的名字和密码的，而且role也不能修改为user之上的级别。
           updateWrapper.set("state",user.getState());
           updateWrapper.set("role",user.getRole());
           long rows = userMapper.update(user,updateWrapper);
           if(rows > 0){
               User newUser = userMapper.selectById(user.getUsername());
               return CommonResponse.createForSuccess(newUser);
           }
           else {
               return CommonResponse.createForError("update failed");
           }
       }
       else return CommonResponse.createForError("admin can just update users' information");

    }

    @Override
    public CommonResponse<Object> selectUser(String usernameList) {
       List<User> userLists = new ArrayList<>();
       List<String> userNameList = new ArrayList<>();
        StringTokenizer username = new StringTokenizer(usernameList,",");//以逗号分隔每个用户的名字,并存在list里面
        while(username.hasMoreTokens()){
            String usernameWORD = username.nextToken();
            userNameList.add(usernameWORD.toString());
        }
        for(Object name : userNameList){
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("username",name);
            userLists.add(userMapper.selectOne(queryWrapper));
        }
        if(userLists.size() == 0){
            log.error("userLists is null");
            return CommonResponse.createForError("no such users , check your names and format");
        }
        else{
            List<Api> relationalApis = apiService.getRelationalApis(11);
            return CommonResponse.createForSuccessIncludeApis(userLists, relationalApis);
        }
    }

    @Override
    public CommonResponse<Object> modifyUserPassword(String username, String password) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        User user = userMapper.selectOne(queryWrapper);
        if(user == null){
            return CommonResponse.createForError("no such user.");
        }
        else {
            if(Objects.equals(user.getRole(), Constant.Role.USER)){
                UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq("username",username);
                updateWrapper.set("password",password);
                int row = userMapper.update(user,updateWrapper);
                if(row > 0){
                    User newUser = userMapper.selectById(username);
                    return CommonResponse.createForSuccess(newUser);
                }
                else {
                    return CommonResponse.createForError("change password failed");
                }
            }
            else return CommonResponse.createForError("admin can just modify users' password");

        }
    }

    @Override
    public CommonResponse<Object> banUser(String username) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        User user = userMapper.selectOne(queryWrapper);
        if(user == null){
            return CommonResponse.createForError("no such user.");
        }
        User targetUser = userMapper.selectById(username);
        if(targetUser.getRole().equals(Constant.Role.USER)){
            UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("username",username);
            updateWrapper.set("state", Constant.USER_STATE.DISABLE);
            int row = userMapper.update(user,updateWrapper);
            if(row > 0){
                User newUser = userMapper.selectById(username);
                return CommonResponse.createForSuccess(newUser);
            }
            else {
                return CommonResponse.createForError("ban user failed");
            }
        }
        else return CommonResponse.createForError("admin can just ban user");

    }

    @Override
    public CommonResponse<Object> defrostUser(String username) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        User user = userMapper.selectOne(queryWrapper);
        if(user == null){
            return CommonResponse.createForError("no such user.");
        }
        User targetUser = userMapper.selectById(username);
        if(targetUser.getRole().equals(Constant.Role.USER)){
            UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("username",username);
            updateWrapper.set("state", Constant.USER_STATE.ABLE);
            int row = userMapper.update(user,updateWrapper);
            if(row > 0){
                User newUser = userMapper.selectById(username);
                return CommonResponse.createForSuccess(newUser);
            }
            else {
                return CommonResponse.createForError("defrost user failed");
            }
        }
        else return CommonResponse.createForError("admin can just defrost user");

    }
}
